package com.libl.controller;

import com.libl.pojo.*;
import com.libl.service.*;
import com.libl.util.ResponseUtil;
import com.libl.vo.CatVo;
import com.libl.vo.GoodsAllinone;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/goods")
public class DtsGoodsController {

    @Autowired
    DtsGoodsService goodsService;

    @Autowired
    DtsBrandService brandService;
    /**
     * 商品的列表查询
     * 1，如果管理员是品牌制造商，只能查询该品牌的数据
     * 2，如果管理是其他管理员，可以查询所有的商品数据
     *
     * @param page
     * @param limit
     * @param goodsSn
     * @param name
     * @param sort
     * @param order
     * @return
     */
    @GetMapping("/list")
    public Object list(@RequestParam(value = "page",required = false, defaultValue = "1") Integer page,
                       @RequestParam(value = "limit",required = false, defaultValue = "20") Integer limit,
                       String goodsSn , String name, String sort, String order){
        //获取认证后的主体对象
        Subject subject = SecurityUtils.getSubject();
        DtsAdmin admin = (DtsAdmin) subject.getPrincipal();

        List<Integer> brandIds = null;

        //判断是否是品牌制造商,查询相应品牌的商品数据
        if(subject.hasRole("品牌制造商")) {
            //查询管理员相应的品牌id
            brandIds = brandService.findBrandIdsByAdminId(admin.getId());
        }

        Map<String,Object> data = goodsService.queryPage(page, limit, goodsSn, name, sort, order, brandIds);

        return ResponseUtil.ok(data);
    }

    @Autowired
    DtsCategoryService categoryService;
    /**
     * 查询分类和品牌数据
     * data: {
     *     brandList:[],
     *     categoryList:[]
     * }
     */
    @GetMapping("/catAndBrand")
    public Object catAndBrand(){
        //获取认证后的subject
        Subject subject = SecurityUtils.getSubject();
        DtsAdmin admin = (DtsAdmin) subject.getPrincipal();

        List<Integer> brandIds = null;
        //获取品牌数据
        //如果是品牌制造商，只查询该管理员对应的品牌信息
        //判断是否是品牌制造商,查询相应品牌的商品数据
        if(subject.hasRole("品牌制造商")) {
            //查询管理员相应的品牌id
            brandIds = brandService.findBrandIdsByAdminId(admin.getId());
        }
        //获取品牌列表数据
        List<Map<String,Object>> brandList = brandService.findBrandList(brandIds);

        //获取分类数据
        List<CatVo> categoryList = categoryService.findCategoryList();

        //数据的封装
        Map<String,Object> data = new HashMap<>();
        data.put("brandList", brandList);
        data.put("categoryList", categoryList);

        return ResponseUtil.ok(data);
    }

    //属性
    @Autowired
    DtsGoodsAttributeService attributeService;
    //规格
    @Autowired
    DtsGoodsSpecificationService specificationService;
    //库存
    @Autowired
    DtsGoodsProductService productService;
    /**
     * data: {
     *     categoryIds: [
     *          一级分类id，
     *          二级分类id
     *     ]，
     *     goods: {
     *         商品详情信息
     *     },
     *     attributes: [
     *          商品的属性信息
     *     ]，
     *     specifications：[
     *          商品的规格信息
     *     ]，
     *     products：[
     *          库存量
     *     ]
     * }
     *
     * @param id
     * @return
     */
    @GetMapping("/detail")
    public Object detail(Integer id){
        //查询商品的详情信息
        DtsGoods goods = goodsService.selectById(id);
        //查询商品的分类id
        Integer categoryL2Id = goods.getCategoryId();
        //根据二级分类id查询一级分类id
        Integer categoryL1Id =  categoryService.findL1ByL2(categoryL2Id);
        Integer[] categoryIds = {categoryL1Id, categoryL2Id};
        //查询商品的属性
        List<DtsGoodsAttribute> attributeList = attributeService.findAttributesByGoodsId(id);
        //查询商品的规格
        List<DtsGoodsSpecification> specificationList = specificationService.findAttributesByGoodsId(id);
        //查询商品的库存量
        List<DtsGoodsProduct> productList = productService.findAttributesByGoodsId(id);

        Map<String,Object> data = new HashMap<>();
        data.put("categoryIds", categoryIds);
        data.put("goods", goods);
        data.put("attributes", attributeList);
        data.put("specifications", specificationList);
        data.put("products", productList);

        return  ResponseUtil.ok(data);
    }

    //更新商品
    @PostMapping("/update")
    public Object update(@RequestBody GoodsAllinone goodsAllinone){
        Object result = checkGoodsData(goodsAllinone);
        //如果result不为空，说明数据有问题，直接响应前端
        if(result != null){
            return  result;
        }
        goodsService.update(goodsAllinone);

        return ResponseUtil.ok();
    }

    private Object checkGoodsData(GoodsAllinone goodsAllinone) {
        //获取商品对象
        DtsGoods goods = goodsAllinone.getGoods();
        if(goods == null){
            return ResponseUtil.fail(-1, "商品不能为空");
        }

        if(StringUtils.isEmpty(goods.getName())){
            return ResponseUtil.fail(-1, "商品名称不能为空");
        }

        if(StringUtils.isEmpty(goods.getGoodsSn())){
            return ResponseUtil.fail(-1, "商品编号不能为空");
        }

        //获取品牌商的id
        Integer brandId = goods.getBrandId();
        //如果品牌商id不为空，则需要判断id是否是有效的
        if(brandId != null){
            DtsBrand brand = brandService.selectById(brandId);
            if(brand == null){
                return ResponseUtil.fail(-1, "品牌商id无效");
            }
        }
        //获取分类id
        Integer categoryId = goods.getCategoryId();
        if(categoryId != null){
            DtsCategory category = categoryService.selectById(categoryId);
            if(category == null){
                return ResponseUtil.fail(-1, "分类id无效");
            }
        }

        //获取商品的属性
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        if(attributes != null && attributes.length > 0){
            for (DtsGoodsAttribute attribute : attributes) {
                if(StringUtils.isEmpty(attribute.getAttribute())){
                    return ResponseUtil.fail(-1, "商品属性名不能为空");
                }
            }
        }
        //获取商品的规格
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        if(specifications != null && specifications.length > 0){
            for (DtsGoodsSpecification specification : specifications) {
                if(StringUtils.isEmpty(specification.getSpecification())) {
                    return ResponseUtil.fail(-1, "商品规格名称不能为空");
                }
            }
        }
        //获取商品的库存
        DtsGoodsProduct[] products = goodsAllinone.getProducts();
        if (products != null && products.length >0){
            for (DtsGoodsProduct product : products) {
                if (StringUtils.isEmpty(product.getSpecifications())){
                    return ResponseUtil.fail(-1, "商品库存不能为空");
                }
            }
        }

        return  null;
    }

    //上架商品
    @PostMapping("/create")
    public Object create(@RequestBody GoodsAllinone goodsAllinone){
        Object result = checkGoodsData(goodsAllinone);
        //如果result不为空，说明数据有问题，直接响应前端
        if(result != null){
            return  result;
        }
        goodsService.save(goodsAllinone);

        return ResponseUtil.ok();
    }

    //下架商品
    @PostMapping("/delete")
    public Object delete(@RequestBody DtsGoods goods){
        goodsService.delete(goods);
        return ResponseUtil.ok();
    }

}
